package com.learn.jdk21.controller;

import com.learn.jdk21.service.AsyncService;
import com.learn.jdk21.service.ThreadPoolReuseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CountDownLatch;

/**
 * @author caiming01
 * @date 2023/10/23 21:07
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private AsyncService asyncService;

    @Autowired
    ThreadPoolReuseService threadPoolReuseService;


    @GetMapping("/async")
    public long testAsync() throws InterruptedException {
        long start = System.currentTimeMillis();
        int n = 100_000;
        CountDownLatch countDownLatch = new CountDownLatch(n);
        for (int i = 0; i < n; i++) {
            asyncService.doSomething(countDownLatch);
        }
        countDownLatch.await();
        long end = System.currentTimeMillis();
        long time = end - start;
        System.out.println("耗时：" + time + "ms");
        return time;
    }


    @GetMapping("/load")
    public void testHttp() throws InterruptedException {
        log.info("Thead {} is virtual : {}", Thread.currentThread(), Thread.currentThread().isVirtual());
        Thread.sleep(1000);
    }

    @GetMapping("/reusep")
    public String testReuseP() {
        return threadPoolReuseService.threadPoolReuse();
    }

    @GetMapping("/reusev")
    public String testReuseV() {
        return threadPoolReuseService.VirtualThreadPoolReuse();
    }
}
